#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <errno.h>
#include <string.h>

#define  fname "/tmp/beyond"

typedef struct _user_t {
	char	name[36];
	int		age;
	short	sex;
} user_t;

user_t *user;

static user_t s_user[10] = {
	{"john", 30, 0},
	{"marry", 31, 1},
	{"jason", 32, 0},
	{"tim", 33, 1},
	{"jondon", 34, 0},
	{"jamson", 35, 0},
	{"wead", 36, 1},
	{"kevin", 37, 0},
	{"kenny", 38, 1},
	{"eason", 39, 0}
};

int user_alloc()
{
	int i = 0;
	int shmid = 0;
	user_t *buf;
	key_t key;

	key = ftok(fname, 2);
	shmid = shmget(key, 1024, IPC_CREAT | IPC_EXCL | 0644);
	if(shmid == -1 && errno == EEXIST)
	{
		printf("shmget result: %s\n", strerror(errno));
		shmid = shmget(key, 1024, 0644);
	}

	buf = (user_t *)shmat(shmid, NULL, 0);
	if(atoi((void *)buf) == -1)
		printf("shmat buf=%p result: %s\n", buf, strerror(errno));

	user = buf;

	printf("copy to buf result: %p\n", buf);
	for(i=0;i<sizeof(s_user)/sizeof(s_user[0]);i++)
	{
		memcpy((void *)buf, (void *)&s_user[i], sizeof(user_t));
		printf("copy to buf result: %s\n", buf->name);
		buf++;
	}

	return 0;
}

int user_read()
{
	int i = 0;
	user_t *buf;

	buf = user;
	for(i=0;i<sizeof(s_user)/sizeof(s_user[0]);i++)
	{
		printf("read share memery name=%s, age=%d, sex=%d\n", buf->name, buf->age, buf->sex);
		buf++;
	}

	return 0;
}

int main(int argc, char **argv)
{
	user_alloc();
	user_read();
	return 0;
}
